﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;
using System.IO;



namespace GenIX
{//<FIELD_WORKING>
    //=====================================РАБОТА С ПОЛЯМИ===================================================     
    //</FIELD_WORKING>
    public partial class NewXML : Form
    {
        int NumberOfFields = 0;
        bool NotView = true;
        MaskedTextBox[] tbName = new MaskedTextBox[100];
        MaskedTextBox[] tbValue = new MaskedTextBox[100];
        ComboBox[] ComboValue = new ComboBox[100];
        DateTimePicker[] DateBox = new DateTimePicker[100];
        string FileName = string.Empty;
        XmlDocument Doc = new XmlDocument();
        TreeNode CurNode, tnode;
        bool written = false;
        bool DTDwritten = false;
        string ProgPath = string.Empty;
        string DTDpath = string.Empty;
        bool DTDexists = false;
        //<ADD_MASKEDTEXTBOX>
        //добавление одного поля MaskedTextBox
        //</ADD_MASKEDTEXTBOX>
        private void PlusOneTb(string FieldName, string ValText, string DateMask, byte Enabld)
        {
            if (numericUpDown1.Value <= 50)
                NumberOfFields++;
            else return;

            tbName[NumberOfFields] = new MaskedTextBox();
            //<TEXT_CHANGING_EVENT>
            //подписка на событие при вводе имени узла
            //</TEXT_CHANGING_EVENT>
            if (checkBox1.Checked == false)
            {
                tbName[NumberOfFields].TextChanged += new EventHandler(this.tbNameChanged);
                tbName[NumberOfFields].Enabled = true;
            }
            else
                tbName[NumberOfFields].Enabled = false;

            tbName[NumberOfFields].Parent = panel1;
            if (NumberOfFields == 1)
            {
                tbName[NumberOfFields].Top = 30;
                tbName[NumberOfFields].Left = 50;
            }
            else
            {
                tbName[NumberOfFields].Top = 30 + tbName[NumberOfFields - 1].Top;
                tbName[NumberOfFields].Left = tbName[NumberOfFields - 1].Left;
            }
            tbName[NumberOfFields].BackColor = SystemColors.Control;
            tbName[NumberOfFields].BorderStyle = BorderStyle.FixedSingle;
            tbName[NumberOfFields].Width = 150;
            tbName[NumberOfFields].Text = FieldName;

            tbValue[NumberOfFields] = new MaskedTextBox();
            tbValue[NumberOfFields].Parent = panel1;
            tbValue[NumberOfFields].Top = tbName[NumberOfFields].Top;
            tbValue[NumberOfFields].Left = tbName[NumberOfFields].Left + 170;
            tbValue[NumberOfFields].Width = 400;
            tbValue[NumberOfFields].Mask = DateMask;
            tbValue[NumberOfFields].Enabled = Convert.ToBoolean(Enabld);
            tbValue[NumberOfFields].Text = ValText;

            if ((AddElementButton.Enabled == false) & (FileName != string.Empty))
                AddElementButton.Enabled = true;

        }
        //<ADDING_COMBOBOX>
        //добавление одного ComboBox
        //</ADDING_COMBOBOX>
        private void PlusOneCmbBox(string FieldName, string ValList, string RusName)
        {
            NumberOfFields++;

            tbName[NumberOfFields] = new MaskedTextBox();

            tbName[NumberOfFields].Parent = panel1;
            tbName[NumberOfFields].Enabled = false;

            tbName[NumberOfFields].Top = 30 + tbName[NumberOfFields - 1].Top;
            tbName[NumberOfFields].Left = tbName[NumberOfFields - 1].Left;

            tbName[NumberOfFields].BackColor = SystemColors.Control;
            tbName[NumberOfFields].BorderStyle = BorderStyle.FixedSingle;
            tbName[NumberOfFields].Width = 150;
            tbName[NumberOfFields].Text = FieldName;

            ComboValue[NumberOfFields] = new ComboBox();

            if (NumberOfFields != 2)
                ComboValue[NumberOfFields].DropDownStyle = ComboBoxStyle.DropDownList;
            ComboValue[NumberOfFields].Parent = panel1;
            ComboValue[NumberOfFields].Top = tbName[NumberOfFields].Top;
            ComboValue[NumberOfFields].Left = tbName[NumberOfFields].Left + 170;
            ComboValue[NumberOfFields].Width = 400;
            ComboValue[NumberOfFields].Name = ValList;
            ComboValue[NumberOfFields].Tag = RusName;
        }

        //<ADDING_DATEBOX>
        //добавление одного ComboBox
        //</ADDING_DATEBOX>
        private void PlusOneDateBox(string FieldName, string Date,bool time, bool enabled)
        {
            NumberOfFields++;

            tbName[NumberOfFields] = new MaskedTextBox();

            tbName[NumberOfFields].Parent = panel1;
            tbName[NumberOfFields].Enabled = false;

            tbName[NumberOfFields].Top = 30 + tbName[NumberOfFields - 1].Top;
            tbName[NumberOfFields].Left = tbName[NumberOfFields - 1].Left;

            tbName[NumberOfFields].BackColor = SystemColors.Control;
            tbName[NumberOfFields].BorderStyle = BorderStyle.FixedSingle;
            tbName[NumberOfFields].Width = 150;
            tbName[NumberOfFields].Text = FieldName;

            DateBox[NumberOfFields] = new DateTimePicker();
            DateBox[NumberOfFields].Format = DateTimePickerFormat.Custom;
            if (time == true)
            DateBox[NumberOfFields].CustomFormat = "dd.MM.yyyy HH:mm";
            else
            DateBox[NumberOfFields].CustomFormat = "dd.MM.yyyy";
            DateBox[NumberOfFields].Parent = panel1;
            DateBox[NumberOfFields].Top = tbName[NumberOfFields].Top;
            DateBox[NumberOfFields].Left = tbName[NumberOfFields].Left + 170;
            DateBox[NumberOfFields].Width = 400;
            DateBox[NumberOfFields].Text = Date;
            DateBox[NumberOfFields].Enabled = enabled;
        }

        //<FIELD_ERASING>
        //удаление лишнего поля ввода 
        //</FIELD_ERASING>
        private void DecFields(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true && NumberOfFields > 0)
                EraseAllFields(0, e);

            NotView = true;
            if (NumberOfFields > 3)
            {
                tbName[NumberOfFields].Dispose();
                tbValue[NumberOfFields].Dispose();
                NumberOfFields--;
            }
            else
                EraseAllFields(0, e);

            if (NumberOfFields > 0)
                numericUpDown1.Value = NumberOfFields;
        }

        //<ERASE_ALL_FIELDS>
        //удаление всех полей
        //</ERASE_ALL_FIELDS>
        private void EraseAllFields(object sender, EventArgs e)
        {
            byte j = 0;
            if (NumberOfFields > 0)
            {
                panel1.Controls.Clear();

                NumberOfFields = 0;
                AddElementButton.Enabled = false;
            }
            if (!written & !DTDwritten)
            {
                checkBox1.Enabled = true;
                numericUpDown1.Enabled = true;
            }
            if (DTDwritten)
                checkBox1.Enabled = false;


            IncFieldButton.Enabled = DecFieldButton.Enabled = true;
            numericUpDown1.Value = NumberOfFields;
            NotView = true;

        }

        //<ADD_FIELDS>
        //обработчик события при щелчке кнопки добавления полей
        //</ADD_FIELDS>
        private void AddFields(object sender, EventArgs e)
        {

            if (numericUpDown1.Value > 50) numericUpDown1.Value = 50;
            if (checkBox1.Checked == false)
            {
                AnyFields();
                Styleform.SelectElement(this, Styleform.choseStyleName);
            }
            else
            {
                DefaultFields();
                Styleform.SelectElement(this, Styleform.choseStyleName);
            }
        }

        //<DEF_FIELDS>
        //вывод стандартного набора полей 
        //<DEF_FIELDS>
        private void DefaultFields()
        {
            int CurID = 0;
            int i = 0;
            byte tbEnabld = 1;
            string mask = string.Empty;
            string ValueText = string.Empty;
            XmlNode root = Doc.DocumentElement;
            XmlNodeList rows = root.ChildNodes;
            CurID = rows.Count;
            EraseAllFieldsButton.PerformClick();
            numericUpDown1.Enabled = false;

            MainForm mainform = this.Owner as MainForm;

            for (i = 0; i < DefaultNames.Length; i++)
            {
                switch (i + 1)
                {
                    case 2: PlusOneCmbBox(DefaultNames[i], ComboAssignPerson, "Назначено"); break;

                    case 4: PlusOneDateBox(DefaultNames[i],"",false,true); break;

                    case 5: PlusOneCmbBox(DefaultNames[i], ComboStatus, "Статус"); break;

                    case 6: PlusOneCmbBox(DefaultNames[i], ComboImportnance, "Важность"); break;

                    case 7: PlusOneCmbBox(DefaultNames[i], ComboUrgency,"Срочность"); break;

                    case 8: PlusOneDateBox(DefaultNames[i], DateTime.Now.ToString(),true,false); break;

                    case 9: PlusOneDateBox(DefaultNames[i], DateTime.Now.ToString(),true, false); break;

                    case 10: mask = string.Empty; ValueText = mainform.tbCurUser.Text; tbEnabld = 0; 
                             PlusOneTb(DefaultNames[i],ValueText, mask, tbEnabld); break;

                    case 11: mask = string.Empty; ValueText = mainform.tbCurUser.Text; tbEnabld = 0; 
                             PlusOneTb(DefaultNames[i],ValueText, mask, tbEnabld); break;

                    case 12: PlusOneCmbBox(DefaultNames[i], ComboProgress , "Степень выполнения"); break;

                    case 13: PlusOneDateBox(DefaultNames[i], "",false, true); break;

                    default: mask = string.Empty; ValueText = string.Empty; tbEnabld = 1; 
                             PlusOneTb(DefaultNames[i],ValueText, mask, tbEnabld); break;
                }
            }
            IncFieldButton.Enabled = false;
            DecFieldButton.Enabled = false;

            tbValue[1].Text = CurID.ToString();
            tbValue[1].Enabled = false;

            checkBox1.Enabled = false;
        }

        //<ANY_FIELDS>
        //добавление произвольного набора полей ввода параметров
        //</ANY_FIELDS>
        private void AnyFields()
        {
            NotView = true;
            int CurID = 0;

            XmlNode root = Doc.DocumentElement;
            XmlNodeList rows = root.ChildNodes;
            CurID = rows.Count;

            checkBox1.Enabled = false;

            if (NumberOfFields == 0)
            {
                int h = 0;
                for (h = 1; h <= 3; h++)
                {
                    tbName[h] = new MaskedTextBox();
                    tbName[h].Parent = panel1;
                    tbName[h].Top = 30 * h;
                    tbName[h].BackColor = SystemColors.Control;
                    tbName[h].BorderStyle = BorderStyle.FixedSingle;
                    tbName[h].Width = 150;

                    if (h == 1)
                        tbName[h].Left = 20;
                    else tbName[h].Left = tbName[h - 1].Left;

                    tbValue[h] = new MaskedTextBox();
                    tbValue[h].Parent = panel1;
                    tbValue[h].Top = 30 * h;
                    tbValue[h].Left = tbName[h].Left + 170;
                    tbValue[h].Width = 400;
                    switch (h)
                    {
                        case 1: tbName[1].Text = "TASK_ID";
                            tbValue[1].Text = Convert.ToString(CurID);
                            tbValue[1].Enabled = false;
                            tbName[1].Enabled = false;
                            break;
                        case 2: tbName[2].Text = "ASSIGN_TO";
                            tbName[2].Enabled = false;
                            break;
                        case 3: tbName[3].Text = "TASK_NAME";
                            tbName[3].Enabled = false;
                            break;
                    }
                }
                if ((AddElementButton.Enabled == false) & (FileName != string.Empty))
                    AddElementButton.Enabled = true;
                NumberOfFields = 3;
            }

            else
                PlusOneTb("DEFAULT" + (NumberOfFields + 1).ToString(), string.Empty, string.Empty, 1);
            panel1.ScrollControlIntoView(tbName[NumberOfFields]);
            panel1.Focus();
            numericUpDown1.Value = NumberOfFields;
            Styleform.SelectElement(this, Styleform.choseStyleName);
        }

        //<VALID_NAME>
        //проверка правильности ввода имени узла 
        //</VALID_NAME>
        void tbNameChanged(object sender, EventArgs e)
        {
            MaskedTextBox tb = (MaskedTextBox)sender;
            if (tb.Text == "")
                tb.BackColor = Color.Salmon;
            else
                tb.BackColor = SystemColors.Control;
            string CorText = "";
            Regex rgx = new Regex(@"^[a-zA-Z0-9-_:]$");
            for (int ChIndex = 0; ChIndex < tb.Text.Length; ChIndex++)
            {
                if (
                    (rgx.IsMatch(tb.Text[ChIndex].ToString()) &&
                    ((char.IsDigit(tb.Text[0]) == false) &&
                    (tb.Text[0] != ':') && (tb.Text[0] != '-')))
                    )

                    if (
                        !(
                        (tb.TextLength > 2) && (
                        (tb.Text[0] == 'X' | tb.Text[0] == 'x') &&
                        (tb.Text[1] == 'M' | tb.Text[1] == 'm') &&
                        (tb.Text[2] == 'L' | tb.Text[2] == 'l'))
                        )
                        )
                    {
                        CorText += tb.Text[ChIndex];
                    }
            }
            tb.Text = CorText;
            tb.SelectionStart = tb.Text.Length;
        }

        private void NewFileButton_Click(object sender, EventArgs e)
        {
            CreateFile();
        }
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            ProgPath = Application.ExecutablePath;
            DTDpath = Path.GetDirectoryName(ProgPath) + "\\DTD\\ROWS.dtd";

            string Folder = string.Empty;
            Folder = Path.GetDirectoryName(FileName);
            if (!File.Exists(DTDpath) & checkBox1.Checked)
            {
                MessageBox.Show("Не найден файл DTD!" + DTDpath, null, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                checkBox1.Checked = false;
            }
        }

        private void NewXML_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (FileName != "")
                if ((DTDexists == false) & (File.Exists(Path.GetDirectoryName(FileName) + "\\ROWS.dtd")))
                    File.Delete(Path.GetDirectoryName(FileName) + "\\ROWS.dtd");
        }
    }
}








